<template>
  <div class="box-home" v-loading="pageLoading" loading-tip="数据获取中...">
    <div class="home-header">
      <div class="header-from">
        <div class="from-input">
          <div class="input-label">渠道名称</div>
          <div class="input-value">
            <AllSelect
              v-model:selectValue="stateData.channelCode"
              :key="stateData.selectKey"
              :maxTagCount="6"
              :disabledSelect="stateData.channelList.length === 1"
              :options="channelTreeData"
            />
          </div>
          <a-button class="input-btn" type="primary" :disabled="stateData.channelList.length === 1" @click="getData">
            查询
          </a-button>
        </div>
      </div>
    </div>
    <div class="home-total">
      <div class="total-num">
        <div class="global-title">统计汇总</div>
        <div class="total-box">
          <div class="box-item">
            <div class="item-tenant">
              <div class="tenant-icon">
                <img :src="tenantNum" />
              </div>
              <div class="tenant-data">
                <div class="data-name">当前服务租户数量</div>
                <div class="data-num">{{ stateData.totalNum.topOrgCount || 0 }}</div>
              </div>
            </div>
            <div class="item-tenant">
              <div class="tenant-icon"></div>
              <div class="tenant-data">
                <div class="data-num data-num-not">{{ stateData.totalNum.unAuthOrgCount || 0 }}</div>
                <div class="data-name">未认证</div>
              </div>
            </div>
          </div>
          <div class="box-item">
            <div class="item-tenant">
              <div class="tenant-icon">
                <img :src="companyNum" />
              </div>
              <div class="tenant-data">
                <div class="data-name">当前服务企业数量</div>
                <div class="data-num">{{ stateData.totalNum.orgCount || 0 }}</div>
              </div>
            </div>
            <div class="item-tenant">
              <div class="tenant-icon"></div>
              <div class="tenant-data">
                <div class="data-num data-num-authed">{{ stateData.totalNum.authOrgCount || 0 }}</div>
                <div class="data-name">已认证</div>
              </div>
            </div>
          </div>
          <div class="box-item box-flex">
            <div class="item-tenant">
              <div class="tenant-icon"></div>
              <div class="tenant-data">
                <div class="data-num data-num-auth">{{ stateData.totalNum.invoiceSuccessOrgCount || 0 }}</div>
                <div class="data-name">已开票</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="total-message">
        <div class="global-title">消息中心</div>
        <div class="message-list">
          <div class="list-scroll">
            <div class="scroll-item" v-for="(item, index) in stateData.messageList" :key="item.id">
              <a-tooltip>
                <template #title>{{ item.titleContent }}</template>
                <div class="item-title" v-html="item.title"></div>
              </a-tooltip>
              <div class="item-createTime">{{ item.createTime }}</div>
            </div>
          </div>
          <!-- <vue3-seamless-scroll :step="0.5" :hover="true" :list="stateData.messageList" class="list-scroll">
            <div class="scroll-item" v-for="(item, index) in stateData.messageList" :key="item.id">
              <a-tooltip>
                <template #title>{{ item.titleContent }}</template>
                <div class="item-title" v-html="item.title"></div>
              </a-tooltip>
              <div class="item-createTime">{{ item.createTime }}</div>
            </div>
          </vue3-seamless-scroll> -->
          <Empty v-if="stateData.messageList.length === 0"></Empty>
        </div>
      </div>
    </div>
    <div class="home-bar">
      <div class="global-title">新增企业数量</div>
      <div class="bar-box" v-loading="numLoading" loading-tip="数据获取中...">
        <div class="box-time">
          <a-radio-group v-model:value="timeState.dateType" @change="getBarData">
            <a-radio-button :value="1">按日</a-radio-button>
            <a-radio-button :value="2">按月</a-radio-button>
          </a-radio-group>
          <div class="time-select">
            <div class="select-txt">统计时间</div>
            <a-range-picker
              v-model:value="timeState.timeDate"
              v-if="timeState.dateType === 1"
              :allowClear="false"
              valueFormat="YYYY-MM-DD"
              format="YYYY-MM-DD"
              :disabled-date="disabledDate"
            />
            <a-range-picker
              v-model:value="timeState.monthDate"
              :placeholder="['开始月份', '结束月份']"
              v-else-if="timeState.dateType === 2"
              picker="month"
              :allowClear="false"
              valueFormat="YYYY-MM"
              format="YYYY-MM"
              :disabled-date="monthDisabledDate"
            />
            <a-button class="input-btn" style="margin-left: 16px" type="primary" @click="getBarData"> 查询 </a-button>
          </div>
        </div>
        <div style="height: 350px" v-if="stateData.companyBarOptions.series === undefined">
          <Empty></Empty>
        </div>
        <CustomChart :key="chartKey" v-else :option="stateData.companyBarOptions" height="350px"></CustomChart>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, computed, onActivated } from 'vue'
import PageWrapper from '@/components/PageWrapper/index.vue'
import AllSelect from '@/components/AllSelect/index.vue'
import { ALL_SELECT } from '@/utils/constantMap'
import { message } from 'ant-design-vue'
import { Vue3SeamlessScroll } from 'vue3-seamless-scroll'
import Empty from '@/components/Empty/index.vue'
import EllipsisTooltip from '@/components/EllipsisTooltip/index.vue'
import CustomChart from '@/components/CustomChart/index.vue'
import { companyBarOptions } from './echartsOption'
import { getBeforeTime, timeDiff } from '@/utils/dateUtil'
import dayjs, { Dayjs } from 'dayjs'
import { createChannelTree, transformToTree } from '@/utils'

import api from '@/api'
const { queryChannelList, queryOrgCount, queryMessagePage, queryOrgCreateCount } = api

import tenantNum from '@/assets/images/tenantNum.png'
import companyNum from '@/assets/images/companyNum.png'

const pageLoading = ref(false)
const numLoading = ref(false)
const chartKey = ref(0)
const stateData = reactive<any>({
  selectKey: 0,
  channelList: [],
  channelCode: [],
  totalNum: {}, // 统计汇总
  messageList: [], // 消息列表
  companyBarOptions: {} // 新增企业数量
})
const channelTreeData = ref<any>([])

const timeState = reactive<any>({
  dateType: 1,
  timeDate: [getBeforeTime(31, 'day'), getBeforeTime(0, 'day')],
  monthDate: [getBeforeTime(6), getBeforeTime(1)]
})
onActivated(() => {
  // 解决KeepAlive缓存页面，其它页面缩放后再回来，图表会变形（无法获取父级宽度，导致宽度为100px）
  chartKey.value++
})

// 选择当天之前时间
const disabledDate = (current: Dayjs) => {
  const today = dayjs().startOf('day') // 获取今天的开始时间
  const selectedDate = dayjs(current).startOf('day') // 获取选中日期的开始时间
  return selectedDate.isAfter(today)
}
const monthDisabledDate = (current: Dayjs) => {
  const currentTime = dayjs(current)
  // 如果当前日期在当前月份之后，则禁用
  return currentTime.isAfter(dayjs().startOf('month'), 'month')
}

const getBarData = async (type: string) => {
  let dateType = timeState.dateType
  let beginDateStr = ''
  let endDateStr = ''
  if (dateType === 1) {
    if (!timeState.timeDate || timeState.timeDate.length === 0) {
      return message.error('请选择统计时间')
    }
    if (Math.abs(timeDiff(timeState.timeDate[0], timeState.timeDate[1], 'day')) > 365) {
      return message.error('您选择的时间区间超过了365天，请重新选择')
    }
    beginDateStr = timeState.timeDate[0]
    endDateStr = timeState.timeDate[1]
  } else if (dateType === 2) {
    if (!timeState.monthDate || timeState.monthDate.length === 0) {
      return message.error('请选择统计时间')
    }
    if (Math.abs(timeDiff(timeState.monthDate[0], timeState.monthDate[1], 'month')) > 24) {
      return message.error('您选择的时间区间超过了24个月，请重新选择')
    }
    beginDateStr = timeState.monthDate[0]
    endDateStr = timeState.monthDate[1]
  }

  let channelCodeSet = stateData.channelCode.filter((item: string) => item !== ALL_SELECT)
  if (type !== 'init') {
    numLoading.value = true
  }
  try {
    let companyBarRes = await queryOrgCreateCount({
      channelCodeSet,
      dateType,
      beginDateStr,
      endDateStr
    })
    numLoading.value = false
    stateData.companyBarOptions = companyBarOptions(companyBarRes.result || [])
  } catch (error) {
    numLoading.value = false
  }
}
const getData = async () => {
  try {
    pageLoading.value = true
    let channelCodeSet = stateData.channelCode.filter((item: string) => item !== ALL_SELECT)
    console.log('参数======>', channelCodeSet)

    // 统计汇总
    let res = await queryOrgCount({
      channelCodeSet
    })
    stateData.totalNum = res.result || {}
    // 消息列表
    let messageRes = await queryMessagePage({
      page: {
        pageNo: 1,
        pageSize: 20
      },
      channelCodeSet
    })
    let messageList = []
    if (messageRes.result && messageRes.result.records) {
      messageList = messageRes.result.records.map((item: any) => {
        return {
          ...item,
          title: `<span style='font-weight: bold'>${item.title}</span>${item.content}`,
          titleContent: `${item.title}${item.content}`,
          id: item.id,
          date: item.createTime
        }
      })
    }
    stateData.messageList = messageList
    // 新增企业数量
    await getBarData('init')
    pageLoading.value = false
  } catch (error) {
    pageLoading.value = false
  }
}
const getQueryChannelList = async () => {
  let res = await queryChannelList()
  let result = res.result || []
  let channelCode: any[] = []
  console.log('result=====>', result)
  channelTreeData.value = transformToTree(result)
  console.log('channelTreeData======>', channelTreeData.value)
  if (result && result.length) {
    result.forEach((item: any) => {
      channelCode.push(item.channelCode)
    })
  }
  stateData.channelCode = channelCode
  stateData.channelList = result
  if (stateData.channelList.length > 1) {
    channelTreeData.value.unshift({
      parentChannelCode: null,
      channelCode: 'ALL_SELECT',
      channelName: '全选'
    })
  }
  stateData.selectKey++
  getData()
}
onMounted(() => {
  getQueryChannelList()
})
</script>

<style lang="less" scoped>
.home-header {
  min-height: 96px;
  padding: 16px;
  border-radius: 4px;
  border: 1px solid #e0e1e6;
  background-color: #fff;
  .header-from {
    min-height: 64px;
    background: #fafafa;
    padding-left: 40px;
    box-shadow: inset 0px -1px 0px 0px #e0e1e6, inset 0px 1px 0px 0px #e0e1e6;
    display: flex;
    align-items: center;
    .from-input {
      display: flex;
      align-items: center;
      .input-label {
        line-height: 22px;
        font-size: 12px;
        font-weight: 600;
        margin-right: 4px;
      }
      .input-value {
        min-width: 280px;
        margin-right: 16px;
      }
      .input-btn {
        &[disabled] {
          color: #fff;
          background: #cdcdcd;
          border-color: #cdcdcd;
        }
      }
    }
  }
}
.home-total {
  width: 100%;
  margin: 16px 0;
  min-height: 245px;
  display: flex;
  justify-content: space-between;
  .total-num,
  .total-message {
    width: calc(36% - 8px);
    background-color: #fff;
    border-radius: 4px;
    border: 1px solid #e0e1e6;
  }
  .total-num {
    width: calc(64% - 8px);
  }
  .total-box {
    padding: 32px 24px;
    display: flex;
    justify-content: space-around;
    .box-flex {
      display: flex;
      align-items: flex-end;
      .item-tenant {
        &:first-child {
          margin-bottom: 0;
        }
      }
    }
    .item-tenant {
      display: flex;
      align-items: center;
      &:first-child {
        margin-bottom: 16px;
      }
      .tenant-icon {
        width: 56px;
        height: 56px;
        margin-right: 8px;
        flex-shrink: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        img {
          width: 100%;
          height: 100%;
        }
      }
      .data-name {
        color: #192235;
        line-height: 22px;
        font-size: 12px;
      }
      .data-num {
        font-size: 24px;
        font-weight: 600;
        color: #4aa353;
        line-height: 22px;
      }
      .data-num-auth {
        color: #5dc966;
        font-size: 18px;
      }
      .data-num-authed {
        color: #377e43;
        font-size: 18px;
      }
      .data-num-not {
        color: #d7802e;
        font-size: 18px;
      }
    }
  }
  .message-list {
    height: 190px;
    padding: 16px 24px;
    position: relative;
    .list-scroll {
      height: 100%;
      overflow-x: hidden;
      overflow-y: auto;
      // overflow: hidden;
      .scroll-item {
        height: 42px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-bottom: 1px solid #e8e8e8;
        .item-title {
          color: #192236;
          font-size: 12px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .item-createTime {
          flex-shrink: 0;
          color: #192236;
          font-size: 12px;
          margin-left: 16px;
        }
      }
    }
  }
}
.home-bar {
  width: 100%;
  background-color: #fff;
  border-radius: 4px;
  border: 1px solid #e0e1e6;
  .bar-box {
    position: relative;
    .box-time {
      position: absolute;
      top: 16px;
      left: 16px;
      display: flex;
      align-items: center;
      z-index: 99;
      .time-select {
        margin-left: 40px;
        display: flex;
        align-items: center;
        .select-txt {
          font-size: 12px;
          font-weight: 600;
          color: #192235;
          line-height: 22px;
          margin-right: 4px;
        }
      }
    }
  }
}
.global-title {
  height: 56px;
  padding-left: 24px;
  font-weight: 600;
  font-size: 14px;
  color: #182035;
  line-height: 56px;
  border-bottom: 1px solid #e0e1e6;
}
</style>
